package com.enhe.gck.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.enhe.gck.CarbonBaseConstant;
import com.enhe.gck.CarbonRelationType;
import com.enhe.gck.communal.PublicMethod;
import com.enhe.gck.item.ClassesHWANE21232Item;
import com.enhe.gck.item.WovenBagHWANE21190Item;
import com.enhe.gck.pojo.WovenBag;
import com.enhe.gck.utils.DateUtil;
import com.kuangkie.carbon.enun.SortDirection;
import com.kuangkie.carbon.panel.CarbonPanel;
import com.kuangkie.carbon.record.RecordQueryFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 编织袋service
 */
@Slf4j
@Service
public class WovenBagService {

    public Optional<WovenBag> getWovenBagNow() {
        RecordQueryFactory queryFactory = CarbonPanel.getRecordQueryFactory(CarbonBaseConstant.编织袋管理_bzdgl);
        queryFactory.getProConJunctionFactory()
                .addEqual(WovenBagHWANE21190Item.基本属性组_日期, LocalDate.now())
                .addEqual(WovenBagHWANE21190Item.基本属性组_转交确认, false)
                .addEqual(WovenBagHWANE21190Item.基本属性组_确认, true)
                .addEqual(WovenBagHWANE21190Item.基本属性组_删除, false)
                .getRelationCriterionFactory(CarbonBaseConstant.班次管理_bcgl)
                .setInRelationTypes(CarbonRelationType.RR_编织袋管理_班次_班次管理)
                .getGuestJunctionFactory()
                .addEqual(ClassesHWANE21232Item.基本属性组_是否删除, false);
        List<WovenBag> wovenBagList = queryFactory
                .addSortItem(PublicMethod.createTimeStr(CarbonBaseConstant.编织袋管理_bzdgl), SortDirection.ASC)
                .queryBeans(WovenBag.class, 2);

        if (CollectionUtil.isEmpty(wovenBagList)) {
            return Optional.empty();
        }

        LocalTime nowTime = LocalTime.now();

        Optional<WovenBag> wovenBagOptional = Optional.empty();
        for (WovenBag wovenBag : wovenBagList) {
            if (Objects.isNull(wovenBag.getClasses())) {
                continue;
            }
            String timeFrame = wovenBag.getClasses().getTime();
            if (DateUtil.withinTheTimeFrame(nowTime, timeFrame)) {
                wovenBagOptional = Optional.of(wovenBag);
                break;
            }
        }
        return wovenBagOptional;
    }

}
